package com.tg.sieve_data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tg.sieve_data.entity.Region;
import com.tg.sieve_data.mapper.RegionMapper;
import com.tg.sieve_data.service.RegionService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    @Override
    public List<Region> getTreeData() {
        // 查询所有地区数据
        List<Region> allRegions = this.list();

        // 获取所有国家级别数据（parentId = 0）
        return allRegions.stream()
                .filter(region -> region.getParentId() == 0)
                .map(region -> buildTree(region, allRegions))
                .collect(Collectors.toList());
    }

    private Region buildTree(Region parent, List<Region> allRegions) {
        // 查找当前节点的所有子节点
        List<Region> children = allRegions.stream()
                .filter(region -> parent.getId().equals(region.getParentId()))
                .map(region -> buildTree(region, allRegions))  // 递归构建子树
                .collect(Collectors.toList());

        parent.setChildren(children);
        return parent;
    }

    @Override
    public List<Region> getByParentId(Integer parentId) {
        return this.list(new QueryWrapper<Region>().eq("parent_id", parentId));
    }
}
